function [s_hat,signal] = sphere_detector_qpsk(h,r,rho,nt,s_tilde)

constellation_size=4;
[q,u]=qr(h);
init_point=exp(j*-3*pi/4)*ones(nt,1);
radius=get_euclidean_distance(s_tilde,100000*init_point)+1;	%added 1 to allow for the equals case

tree=zeros(nt,constellation_size);
s_hat=init_point;
counter=0;

while(sum(sum(tree,2)==1)~=nt  & counter<4000)
	counter=counter+1;
	tree=zeros(nt,constellation_size);
%	tree(nt,:)=ones(constellation_size,1);
	i=nt;
	s_hat=zeros(nt,1);
	while(i>0)
		counter=counter+1; 
		[s_possible,s_min]=full_equation2(u,s_hat,s_tilde,nt,i,radius);
		if(s_min==-1)
			flag=0;
			while(flag==0 & i~=nt+1)
				i=i+1;
				[s_hat(i),flag,tree]=retreat_tree_qpsk(s_hat,tree,i,nt);
			end
			i=i-1;	
		else
			tree(i,s_possible)=1;
			s_hat(i)=s_min;
			i=i-1;
		end

		
	end
	if(get_euclidean_distance(s_tilde,s_hat)<radius)
		s_final=s_hat;
		radius=get_euclidean_distance(s_tilde,s_hat);
	end
end
if(counter==4000)
s_hat=s_final;
end

signal=[];
for m=1:length(r)
	signal=horzcat(signal,qpsk2bin(s_hat(m)));
end







function [s_possible,s_min]=full_equation2(u,s_hat,s_tilde,nt,start,radius)
%if smin returns -1 then we have to go up a level in the tree
theta=[-3*pi/4 3*pi/4 -pi/4 pi/4];
s_try=exp(j*theta);
new_s_hat=s_hat;
for k=1:length(s_try)
	new_s_hat(start)=s_try(k);
	test_radius(k)=get_euclidean_distance(s_tilde(start:nt),new_s_hat(start:nt));
end
s_possible=find(test_radius<=radius);
if(length(s_possible)>0)
	[minimum,s_min]=min(test_radius);
	s_min=s_try(s_min);
	s_min=s_try(s_possible(ceil(rand*length(s_possible))));
else
	s_min=-1;
end




function rad=get_euclidean_distance(r,r_hat)
rad=norm(abs(r-r_hat));
